<?php
function pt($data){
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}
function urlSkip($flag = '', $url = '', $isOk = 0) {
	$flag = $isOk ? ($flag !== false ? '操作成功' : '操作失败') : $flag;
	$flag = $flag ? 'alert("' . $flag . '"); ' : '';
	echo '<script type="text/javascript">' . $flag . 'location.href="' . $url . '"</script>';
	die ();
}
function urlSkipBack($flag = 0, $isOk = 0) {
	$flag = $isOk ? ($flag !== false ? '操作成功' : '操作失败') : $flag;
	$flag = $flag ? 'alert("' . $flag . '"); ' : '';
	echo '<script type="text/javascript">' . $flag . 'history.back(-1); </script>';
	die ();
}
function urlSkipReload($flag = '', $isOk = 0) {
	$flag = $isOk ? ($flag !== false ? '操作成功' : '操作失败') : $flag;
	$flag = $flag ? 'alert("' . $flag . '"); ' : '';
	echo '<script type="text/javascript">' . $flag . 'location.reload();</script>';
	die ();
}

function getCount($oldarray, $array = array(), $string = '') {
	if (preg_match ( '/' . implode ( '', $oldarray ) . '/', $string )) {
		return $string;
	}
	$array = $array ? $array : $oldarray;
	$i = 0;
	$string1 = $string;
	if ($array && count ( $array ) > 1) {
		foreach ( $array as $key => $row ) {
			foreach ( $array as $key1 => $row1 ) {
				if ($row == $row1) {
					continue;
				}
				$flag = $row . $row1;
				foreach ( $oldarray as $key2 => $row2 ) {
					$flag = preg_replace ( '/' . $row2 . $row2 . '/', $row2, $flag );
					$count = preg_match_all ( '/' . $row2 . '/', $flag );
					if ($count > 1) {
						$flag = '';
						break;
					}
				}
				if (! $flag) {
					continue;
				}
				$string .= $string ? ',' . $flag : $flag;
				$newArray [$i] = $flag;
				$i ++;
			}
		}
		$string = getCount ( $oldarray, $newArray, $string );
	}
	return $string;
}

// 获取分类树
function getBtypeId($type_id) {
	$ticketType = D ( 'TicketType' );
	$type_id='0'.$type_id;
	$array = $ticketType->field ('name' )->where ("id IN ($type_id)")->select ();
	$stringFlag = '';
	if ($array) {
		foreach ( $array as $key => $row ) {
			$stringFlag .= $stringFlag ? ' -> ' . $row ['name'] : $row ['name'];
		}
	}
	return $stringFlag;
}
function treeDirectory($dir) 
    {
        $files = array();
        $dirpath = realpath($dir);
        $filenames = scandir($dir);
 
        foreach ($filenames as $filename) 
        {
            if ($filename=='.' || $filename=='..')
            {
                continue;
            }
 
            $file = $dirpath . DIRECTORY_SEPARATOR . $filename;
             
            if (is_dir($file))
            {
                $files = array_merge($files, treeDirectory($file));
            }
            else
            {
                $files[] = $file;
            }
        }
 
        return $files;
    }
/**
 * 重新组装字段
 */
function newField($string, $splitString = '<br />') {
	$string = preg_replace ( '/,/', $splitString, $string );
	return $string;
}

/**
 * 获取类型数组,并重新组装
 */
function getOrderTypeArray() {
	$orderType = D ( 'OrderType' );
	$orderTypeArray = $orderType->where ( ' ishidden = 0' )->select ();
	if ($orderTypeArray) {
		foreach ( $orderTypeArray as $key => $row ) {
			$newArray [$row ['id']] = $row ['type_name'];
		}
	}
	return $newArray;
}
function filterCheck($v) {
	if ($v === "") {
		return false;
	}
	return true;
}

/**
 * 导出数据为excel表格
 *
 * @param $data 一个二维数组,结构如同从数据库查出来的数组
 * @param $title excel的第一行标题,一个数组,如果为空则没有标题
 * @param $filename 下载的文件名
 *        	@examlpe
 *        	$stu = M ('User');
 *        	$arr = $stu -> select();
 *        	exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
 *
 */
function exportexcel($data = array(), $title = array(), $filename = 'report') {
	header ( "Content-type:application/octet-stream" );
	header ( "Accept-Ranges:bytes" );
	header ( "Content-type:application/vnd.ms-excel" );
	header ( "Content-Disposition:attachment;filename=" . $filename . ".xls" );
	header ( "Pragma: no-cache" );
	header ( "Expires: 0" );
	// 导出xls 开始
	if (! empty ( $title )) {
		foreach ( $title as $k => $v ) {
			$title [$k] = iconv ( "UTF-8", "GB2312", $v );
		}
		$title = implode ( "\t", $title );
		echo "$title\n";
	}
	if (! empty ( $data )) {
		foreach ( $data as $key => $val ) {
			foreach ( $val as $ck => $cv ) {
				$data [$key] [$ck] =  iconv ( "UTF-8", "GB2312//IGNORE", $cv );
			}
			$data [$key] = implode ( "\t", $data [$key] );
		}
		echo implode ( "\n", $data );
	}
}

function shexportexcel($data = array(), $title = array(), $filename = 'report') {
	header ( "Content-type:application/octet-stream" );
	header ( "Accept-Ranges:bytes" );
	header ( "Content-type:application/vnd.ms-excel" );
	header ( "Content-Disposition:attachment;filename=" . $filename . ".xls" );
	header ( "Pragma: no-cache" );
	header ( "Expires: 0" );
    header('content-Type:application/vnd.ms-excel;charset=utf-8');
	// 导出xls 开始
	if (! empty ( $title )) {
        //foreach ( $title as $k => $v ) {
        //    $title [$k] = iconv ( "UTF-8", "GB2312", $v );
        //}
        $title1 = returnUtf8($title);
		$title1 = implode ( "\t", $title1 ); 
		echo "$title1\n";
	}

	if (! empty ( $data )) {
        //var_dump($data);
		foreach ( $data as $key => $val ) {
            //    var_dump($data);
            //$val['addtime'] = strtotime($val['addtime']);
            //$key['addtime'] = strtotime($key['addtime']);
            $data2 = array();

            $last = $data[$key]['children'];
            $data[$key]['addtime'] = date('Y-m-d H:i:s',$data[$key]['addtime']);
            $data[$key]['status'] = getMallStatus($data[$key]['status']);
            array_pop($data[$key]);
            // $data=returnUtf8($data);
            $data [$key] = implode ( "\t", $data [$key] );

            foreach($last as $i=>$j){
                //   $last[$i]=returnUtf8($last[$i]);
                $data2[$i]=implode("\t",$last[$i]);
            }
            $data[$key]=$data[$key]."\n".implode("\n",$data2);
		}

        $data1 = returnUtf8($data);
		$data1 = implode ( "\n", $data1 );

		echo "$data1\n";
	}
}

//退货（用户金额变动）
	function return_money_change($store_id,$order_id,$user_id,$money,$other){
		$users_log=M('users_log');
		$data['uid']=$user_id;
		$data['addtime']=time();
		$data['money']=$money;
		$data['type']=1;
		$data['other']=$other;
		$data['store_id']=$store_id;
		$data['order_id']=$order_id;
		$data['money_type']=1;
		$users_log->add($data);
	}
function returnUtf8($data=array()){

    foreach($data as $k=>$v){
        $data[$k]=iconv("UTF-8","GB2312",$v);
    }
    //$data=implode("\t",$data);
    return $data;


}


/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
    //	if(strtolower(CHARSET) == 'utf-8') {
    $length = intval($length-strlen($dot)-$length/3);
    $n = $tn = $noc = 0;
    while($n < strlen($string)) {
        $t = ord($string[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1; $n++; $noc++;
        } elseif(194 <= $t && $t <= 223) {
            $tn = 2; $n += 2; $noc += 2;
        } elseif(224 <= $t && $t <= 239) {
            $tn = 3; $n += 3; $noc += 2;
        } elseif(240 <= $t && $t <= 247) {
            $tn = 4; $n += 4; $noc += 2;
        } elseif(248 <= $t && $t <= 251) {
            $tn = 5; $n += 5; $noc += 2;
        } elseif($t == 252 || $t == 253) {
            $tn = 6; $n += 6; $noc += 2;
        } else {
            $n++;
        }
        if($noc >= $length) {
            break;
        }
    }
    if($noc > $length) {
        $n -= $tn;
    }
    $strcut = mb_substr($string, 0, $n);
    $strcut = str_replace(array('∵', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
  
	return $strcut.$dot;
}
function msubstr($str, $start = 0, $length, $suffix = false, $charset = "utf-8") {
	$strlen = strlen ( $str ) / 2;
	if (function_exists ( "mb_substr" )) {
		if ($suffix && $strlen > $length)
			return mb_substr ( $str, $start, $length, $charset ) . "...";
		else
			return mb_substr ( $str, $start, $length, $charset );
	} elseif (function_exists ( 'iconv_substr' )) {
		if ($suffix && $strlen > $length)
			return iconv_substr ( $str, $start, $length, $charset ) . "...";
		else
			return iconv_substr ( $str, $start, $length, $charset );
	}
	$re ['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
	$re ['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
	$re ['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
	$re ['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
	preg_match_all ( $re [$charset], $str, $match );
	$slice = join ( "", array_slice ( $match [0], $start, $length ) );
	if ($suffix && $strlen > $length) {
		return $slice . "…";
	} else {
		return $slice;
	}
	return $slice;
}

function nsubstr($str, $start = 0, $length, $suffix = false, $charset = "utf-8") {
    $str = strip_tags($str);
	$strlen = strlen ($str) / 2;
	if (function_exists ( "mb_substr" )) {
		if ($suffix && $strlen > $length)
			return mb_substr ( $str, $start, $length, $charset ) . "...";
		else
			return mb_substr ( $str, $start, $length, $charset );
	} elseif (function_exists ( 'iconv_substr' )) {
		if ($suffix && $strlen > $length)
			return iconv_substr ( $str, $start, $length, $charset ) . "...";
		else
			return iconv_substr ( $str, $start, $length, $charset );
	}
	$re ['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
	$re ['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
	$re ['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
	$re ['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
	preg_match_all ( $re [$charset], $str, $match );
	$slice = join ( "", array_slice ( $match [0], $start, $length ) );
	if ($suffix && $strlen > $length) {
		return $slice . "…";
	} else {
		return $slice;
	}
	return $slice;
}


function left($str, $len, $charset="utf-8")
{
    $str = strip_tags($str);
    //如果截取长度小于等于0，则返回空
    if( !is_numeric($len) or $len <= 0 )
    {
        return "";
    }

    //如果截取长度大于总字符串长度，则直接返回当前字符串
    $sLen = strlen($str);
    if( $len >= $sLen )
    {
        return $str;
    }

    //判断使用什么编码，默认为utf-8
    if ( strtolower($charset) == "utf-8" )
    {
        $len_step = 3; //如果是utf-8编码，则中文字符长度为3
    }else{
        $len_step = 2; //如果是gb2312或big5编码，则中文字符长度为2
    }

    //执行截取操作
    $len_i = 0;
    //初始化计数当前已截取的字符串个数，此值为字符串的个数值（非字节数）
    $substr_len = 0; //初始化应该要截取的总字节数

    for( $i=0; $i < $sLen; $i++ )
    {
        if ( $len_i >= $len ) break; //总截取$len个字符串后，停止循环
        //判断，如果是中文字符串，则当前总字节数加上相应编码的中文字符长度
        if( ord(substr($str,$i,1)) > 0xa0 )
        {
            $i += $len_step - 1;
            $substr_len += $len_step;
        }else{ //否则，为英文字符，加1个字节
            $substr_len ++;
        }
        $len_i ++;
    }
    $result_str = substr($str,0,$substr_len );
    return $result_str;
}


function checkImg($img = '') {
	return $img ? $img : '/Home/images/noimg.jpg';
}
function getDocumentRoot() {
	$root = $_SERVER ["DOCUMENT_ROOT"];
	$pattern = '/\\\\/';
	$root = preg_replace ( $pattern, '/', $root );
	$array = explode ( '/', $root );
	if ($array) {
		$root = $array [count ( $array ) - 1] ? $root . '/' : $root;
	}
	return $root;
}
// 时间显示控制 x秒 / x时x分 / x年x月x日
function showTime($time) {
	$nowT = time ();
	$to_now = $nowT - $time; // .date("Y-m-d H:i:s ").
	$day = floor ( $to_now / 3600 / 24 );
	$hour = floor ( $to_now / 3600 );
	$minutes = floor ( $to_now % 3600 / 60 );
	$seconds = $to_now;
	$date = date ( "Y-m-d H:i:s", $time );
	if ($minutes > 0 && $hour < 24) {
		return $hour . "小时" . $minutes . "分钟前";
	} else if ($hour >= 24) {
		return date ( "Y-m-d", $time );
	} else if ($minutes == 0) {
		return $seconds . "秒前";
	}
}





// 无限极菜单
function catetree($cate, $pid = 0, $level = 0, $html = '>') {
	static $tree = array ();
	foreach ( $cate as $v ) {
		if ($v ['bid'] == $pid) {
			$v ['level'] = $level + 1;
			$v ['html'] = str_repeat ( $html, $level );
			$tree [] = $v;
			catetree ( $cate, $v ['id'], $level + 1, $html );
		}
	}
	return $tree;
}
/**
 * 获取当前分类的上下级分类数组
 * $is_for_recycle 是否仅仅调取回收相关分类
 */
function getCurrentTypePC($type_id = '0', $is_for_recycle = '0') {
	$ticketType = D ( 'TicketType' );
	$type_id = $type_id ? $type_id : '0';
	$where = $is_for_recycle ? ' AND is_for_recycle = 1 ' : '';
	// 如果是读取跟节点数据
	if ($type_id == '0') {
		$array ['type'] [0] = $ticketType->field ( 'id,name,bid,bids' )->where ( ' ishidden = 0 AND bid = ' . $type_id . $where )->select ();
	} else {
		$current = $ticketType->field ( 'bids' )->where ( ' ishidden = 0 AND id = ' . $type_id . $where )->find ();
		$idsArray = explode ( ',', '0,' . $current ['bids'] );
		$array ['current'] = $current;
		$array ['ids'] = $idsArray;
		if ($current) {
			$num = count ( $idsArray );
			for($i = 0; $i < $num; $i ++) {
				$array ['type'] [$i] = $ticketType->where ( ' ishidden = 0 AND bid = ' . $idsArray [$i] . $where )->select ();
			}
		}
	}
	return $array;
}




/**
 * 字符串长度限制
 */
function strLimit($len, $str) {
	$str = substr ( $str, 0, $len );
	return $str . '...';
}





// XML格式转数组格式
function xml_to_array( $xml ) {
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches)) {
        $count = count($matches[0]);
        for($i = 0; $i < $count; $i++) {
            $subxml= $matches[2][$i];
            $key = $matches[1][$i];
            if(preg_match( $reg, $subxml )) {
                $arr[$key] = xml_to_array( $subxml );
            } else {
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}


// 清除数组中的空值
function clearArrayNull($array) {
	$array = array_unique ( $array );
	if ($array) {
		foreach ( $array as $key => $row ) {
			if (! $row) {
				continue;
			}
			$newArray [] = $row;
		}
	}
	return $newArray;
}

// 获取处理后的手机号码
function getPhone($phone) {
	return substr ( $phone, 0, 3 ) . '*****' . substr ( $phone, 8, 11 );
}

// 加法运算
function accadd($num1, $num2) {
	$num1 = $num1 * 10 * 10;
	$num2 = $num2 * 10 * 10;
	return bcadd($num1,$num2) / 10 / 10;
}
// 减法运算
function accsub($num1, $num2) {
	$num1 = $num1 * 10 * 10;
	$num2 = $num2 * 10 * 10;
	return bcsub($num1,$num2) / 10 / 10;
}
// 乘法运算
function accmul($num1, $num2) {
	$num1 = $num1 * 10 * 10;
	$num2 = $num2 * 10 * 10;
	return bcmul(bcmul($num1,$num2) / 10 / 10,1) / 10 / 10;
}
// 除法运算
function accdiv($num1, $num2) {
	$num1 = $num1 * 10 * 10;
	$num2 = $num2;
	return bcdiv( $num1,$num2 )/10/10;
}
function getFromType() {
	$agent = $_SERVER ['HTTP_USER_AGENT'];
	if (strpos ( $agent, "NetFront" ) || strpos ( $agent, "iPhone" ) || strpos ( $agent, "MIDP-2.0" ) || strpos ( $agent, "Opera Mini" ) || strpos ( $agent, "UCWEB" ) || strpos ( $agent, "Android" ) || strpos ( $agent, "Windows CE" ) || strpos ( $agent, "SymbianOS" )) {
		return 1;
	}
	return 0;
}
/**
 * 模拟post进行url请求
 * @param string $url
 * @param array $post_data
 */
function request_post($url = '', $post_data = array()) {
    if (empty($url) || empty($post_data)) {
        return false;
    }

    $o = "";
    foreach ( $post_data as $k => $v )
    {
        $o.= "$k=" . urlencode( $v ). "&" ;
    }
    $post_data = substr($o,0,-1);

    $postUrl = $url;
    $curlPost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);

    return $data;
}
function get_url_contents($url) {
	
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	$response = curl_exec ( $ch );
	curl_close ( $ch );
	// }

	// -------请求为空
	if (empty ( $response )) {
		echo $url . '</br>';
		echo "50001";
	}

	return $response;
}
//构造一个请求函数
function http_request($url,$data=array()){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	// 我们在POST数据哦！
	curl_setopt($ch, CURLOPT_POST, 1);
	// 把post的变量加上
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$output = curl_exec($ch);
	curl_close($ch);
	return $output;
}

//生成随机字符串
function randpw($len=8,$format='ALL'){
    $is_abc = $is_numer = 0;
    $password = $tmp ='';
    switch($format){
        case 'ALL':
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			break;
        case 'CHAR':
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
			break;
        case 'NUMBER':
			$chars='0123456789';
			break;
        default :
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			break;
    }
    mt_srand((double)microtime()*1000000*getmypid());
    while(strlen($password)<$len){
        $tmp =substr($chars,(mt_rand()%strlen($chars)),1);
        if(($is_numer <> 1 && is_numeric($tmp) && $tmp > 0 )|| $format == 'CHAR'){
            $is_numer = 1;
        }
        if(($is_abc <> 1 && preg_match('/[a-zA-Z]/',$tmp)) || $format == 'NUMBER'){
            $is_abc = 1;
        }
        $password.= $tmp;
    }
    if($is_numer <> 1 || $is_abc <> 1 || empty($password) ){
        $password = randpw($len,$format);
    }
    return $password;
}


/**
 * 电商Sign签名生成
 * @param data 内容   
 * @param appkey Appkey
 * @return DataSign签名
 */
function encrypt1($data, $appkey) {
    return urlencode(base64_encode(md5($data.$appkey)));
}

/**
 * Json方式 查询订单物流轨迹
 */
function getOrderTracesByJson($ShipperCode,$LogisticCode,$EBusinessID,$AppKey,$ReqURL){
    $requestData= "{'OrderCode':'','ShipperCode':'" . $ShipperCode . "','LogisticCode':'" . $LogisticCode . "'}";

    $datas = array(
        'EBusinessID' => $EBusinessID,
        'RequestType' => '1002',
        'RequestData' => urlencode($requestData) ,
        'DataType' => '2',
    );
    $datas['DataSign'] = encrypt1($requestData, $AppKey);
    $result=sendPost($ReqURL, $datas);

    //根据公司业务处理返回的信息......

    return $result;
}

/**
 *  post提交数据
 * @param  string $url 请求Url
 * @param  array $datas 提交的数据
 * @return url响应返回的html
 */
function sendPost($url, $datas) {
    $temps = array();
    foreach ($datas as $key => $value) {
        $temps[] = sprintf('%s=%s', $key, $value);
    }
    $post_data = implode('&', $temps);
    $url_info = parse_url($url);
    if($url_info['port']=='')
    {
        $url_info['port']=80;
    }
  //  echo $url_info['port'];
    $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
    $httpheader.= "Host:" . $url_info['host'] . "\r\n";
    $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
    $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
    $httpheader.= "Connection:close\r\n\r\n";
    $httpheader.= $post_data;
    $fd = fsockopen($url_info['host'], $url_info['port']);
    fwrite($fd, $httpheader);
    $gets = "";
    $headerFlag = true;
    while (!feof($fd)) {
        if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
            break;
        }
    }
    while (!feof($fd)) {
        $gets.= fread($fd, 128);
    }
    fclose($fd);

    return $gets;
}

//redis
function connectRedis(){
    $redis=new \Redis();
   $redis->connect(C("REDIS_HOST"),C("REDIS_PORT"));       
    return $redis;
}
//查看拼团人数
	function get_tuan($order_id){
		$rs=M('order')->find($order_id);
		if($rs['tuan_is_first_id']==0){
			$count=M('order')->where("tuan_is_first_id=$order_id and order_state>='10'")->count();
		}else{
			$order_id=$rs['tuan_is_first_id'];
			$count=M('order')->where("tuan_is_first_id=$order_id and order_state>='10'")->count();
		}
		return $count+1;
	}
//检查代言资格
 function get_daiyan($shop_id){
 	 $uid=session('user_id');
     $flag=false;
     $rs=M('order')
         ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
         ->where("yt_order_goods.goods_id=$shop_id and yt_order.refund_state='0' and yt_order.buyer_id=$uid and (yt_order.order_state='40' or (yt_order.order_state='20' and yt_order.order_type='2'))")
         ->find();
     if ($rs){
         $flag=true;
     }else{
         $shop=M('shop')->find($shop_id);
         $store_id=$shop['store_id'];
         $type_ids=explode(',',$shop['type_id']);
         foreach ($type_ids as $key=>$value){
         	if($value==null){
         		unset($type_ids[$key]);
			}
		 }
         $type_ids=implode(',',$type_ids);
         $type_id=$type_ids;
         $shop_id=$shop['id'];
         //商品代言
         $rs1=M('angel')->where("type=1 and type_id=$shop_id and uid=$uid")->find();
         //店铺代言
         $rs2= M('angel')->where("type=2 and type_id=$store_id and uid=$uid")->find();
         //分类代言
         $rs3=M('angel')->where('type=3 and type_id  IN ('.$type_id.') and uid='.$uid)->find();


         if($rs1!=null || $rs2!=null ||$rs3!=null){
             $flag=true;
         }
     }
	 //判断城市代言
     if($flag==false){
         $area_angel=M('area_angel');
         $rs=$area_angel->where('uid='.$uid.' and status=4')->select();
         $shop=M('shop')->find($shop_id);
         $store_id=$shop['store_id'];
         $store_info=M('store')->find($store_id);
         if($rs){
             foreach ($rs as $key=>$value){
                 if($value['area_type']==1&&$value['district_id']==$store_info['district']){
                     $flag=true;
                 }
                 if($value['area_type']==2&&$value['city_id']==$store_info['city']){
                     $flag=true;
                 }
                 if($value['area_type']==3&&$value['province_id']==$store_info['province']){
                     $flag=true;
                 }
             }
         }
     }
     return $flag;

 }
//检查代言资格
function get_crowdfunding_daiyan($shop_id){
    $uid=session('user_id');
    $flag=false;
    $rs=M('order')
        ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
        ->where("yt_order_goods.goods_id=$shop_id and yt_order.order_state='20' and yt_order.refund_state='0' and yt_order.buyer_id=$uid ")
        ->find();
    if ($rs){
        $flag=true;
    }else{
        $shop=M('shop')->find($shop_id);
        $store_id=$shop['store_id'];
        $type_ids=explode(',',$shop['type_id']);
        foreach ($type_ids as $key=>$value){
            if($value==null){
                unset($type_ids[$key]);
            }
        }
        $type_ids=implode(',',$type_ids);
        $type_id=$type_ids;
        $shop_id=$shop['id'];
        //商品代言
        $rs1=M('angel')->where("type=1 and type_id=$shop_id and uid=$uid")->find();
        //店铺代言
        $rs2= M('angel')->where("type=2 and type_id=$store_id and uid=$uid")->find();
        //分类代言
        $rs3=M('angel')->where('type=3 and type_id  IN ('.$type_id.') and uid='.$uid)->find();


        if($rs1!=null || $rs2!=null ||$rs3!=null){
            $flag=true;
        }
    }
    return $flag;

}
 function get_daiyan_price($shop_id){
 	$uid=session('user_id');
 	if($uid){
        $invoice=get_web_invoice();
        $start_time=time()-60*60*24*$invoice['web_diyong'];
 		$daiyan_sale_where['uid']=$uid;
		$daiyan_sale_where['shop_id']=$shop_id;
		$daiyan_sale_where['time']=array('GT',$start_time);
		$daiyan_sale=M('daiyan')->where($daiyan_sale_where)->find();
		
		if($daiyan_sale){
			return true;
		}else{
			return false;
		}
 	}else{
 		return false;
 	}
 }
function generate_password($length=8 ) { 
	// 密码字符集，可任意添加你需要的字符 
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#'; 
	$password =''; 
	for ( $i = 0; $i < $length; $i++ ) 
	{ 
		// 这里提供两种字符获取方式 
		// 第一种是使用 substr 截取$chars中的任意一位字符； 
		// 第二种是取字符数组 $chars 的任意元素 
		// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); 
		$password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
	} 
	return $password; 
} 
include 'extend.php';
?>
